package com.bawei.library_base

import android.app.Activity
import android.os.Build
import androidx.annotation.RequiresApi
import java.util.*

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/1 16:37
 * @Description : AppManager   Activity的堆栈管理者
 */
object AppManager {

    private  var activityStack:Stack<Activity> = Stack()

    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity){
        activityStack.add(activity)
    }
    /**
     * 移除指定的Activity
     */
    fun removeActivity(activity: Activity){
        if (activity != null) {
            activityStack.remove(activity)
        }
    }
    /**
     * 是否有activity
     */
    fun isActivity(): Boolean {
        return if (activityStack != null) {
            !activityStack.isEmpty()
        } else false
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity {
        return activityStack.lastElement()
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishActivity() {
        val activity = activityStack.lastElement()
        finishActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        for (activity in activityStack) {
            if (activity.javaClass == cls) {
                finishActivity(activity)
                break
            }
        }
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        activityStack.forEach {
            if(it != null){
                finishActivity(it)
            }
        }
        activityStack.clear()
    }

    /**
     * 获取指定的Activity
     *
     * @author kymjs
     */
    fun getActivity(cls: Class<*>): Activity? {
        if (activityStack != null) {
            activityStack.forEach {
                if(it.javaClass.equals(cls)){
                    return  it
                }
            }
        }
        return null
    }

    /**
     * 根据类的全路径名称获得activity
     */
    fun getActivity(str: String): Activity? {
        if (activityStack != null) {
            activityStack.forEach {
                var name = it.javaClass.name
                var simpleName = it.javaClass.simpleName
                if(it.javaClass.name.equals(str)){
                    return  it
                }
            }
        }
        return null
    }


    /**
     * 退出应用程序
     */
    fun AppExit() {
        try {
            finishAllActivity()
        } catch (e: Exception) {
            activityStack.clear()
            e.printStackTrace()
        }
    }
}